// 这是一款我自己封装的插件
// 之所以取名叫 honey 
// 因为觉得前端的发展神速，导致了前端er学习程序巨大
// const app = getApp();
import config from '../utils/honey.config';
class Honey {
  constructor() {
    const http = new Object();
    this.http = {};
  }
  upload(opt){
    opt.url = config.apiUrl + config.apiPrefix + config.apiMap[opt.alias];
    opt.header = Object.assign(config.header(), opt.header);
    delete opt.alias;
    const cb = opt.success;
    opt.success = function (res) {
    
      const data = JSON.parse(res.data.trim());
      try {
        if (data.status == 1) {
          cb.call(this, data);
        } else {
          wx.showToast({
            icon: 'none',
            title: `错误:${data.msg ? data.msg : ''}`,
          })
        }
      } catch (err) {
        console.log(err.message)
      }
    }
    const uploadTask = wx.uploadFile(opt);
    return uploadTask;
  }
  get(opt) {
    opt.url = config.apiUrl + config.apiPrefix + config.apiMap[opt.alias];
    opt.header = Object.assign(config.header(), opt.header);
    opt.method = 'GET';
    delete opt.alias;
    const cb = opt.success;
    const er = opt.error;
    opt.success = function(res) {
      try {
        if (res.data.status == 1) {
          cb.call(this, res);
        } else {
          if (typeof er === "function") {
            er.call(this, res);
          }
          wx.showToast({
            icon: 'none',
            title: `错误:${res.data.message ? res.data.message : ''}`,
          })
        }
      } catch (err) {
        console.log(err.message)
      }
    }
    wx.request(opt)
  }
  post(opt) {
    opt.url = config.apiUrl + config.apiPrefix + config.apiMap[opt.alias];
    opt.header = Object.assign(config.header(), opt.header);
    opt.method = 'POST';
    delete opt.alias;
    const cb = opt.success;
    const er = opt.error;
    opt.success = function(res) {
      try {
        if (res.data.status == 1) {
          cb.call(this, res);
        } else {
          if (res.data.status == 509) {
            // wx.showToast({
            //   icon: 'none',
            //   title: "登录信息错误，即将返回首页授权登录",
            //   duration:2500
            // })
            // setTimeout(() => {
              wx.removeStorageSync('user')
              wx.removeStorageSync('phone')
              wx.reLaunch({
                url: '/pages/index/index?show=',
              })
            // }, 1500)
          } else {
            if (typeof er === "function") {
              er.call(this, res);
            }
            wx.showToast({
              icon: 'none',
              title: `错误:${res.data.message ? res.data.message : ''}`,
              duration: 2500
            })
          }
        }
      } catch (err) {
        console.log(err.message)
      }
    }
    wx.request(opt)
  }

  
  matchRegular(reg, value) {
    const regEntity = config['regular'][reg];
    const res = new Object();
    if (regEntity.exp.test(value)) {
      res.result = true;
      return res;
    } else {
      res.result = false;
      res.msg = regEntity.text;
      return res;
    }
  }

  showMiniToast(opt) {
    opt.icon = 'none';
    wx.showToast(opt);
  }

  mergeArray(...arg) {
    let newArray = [];
    if (arg.length > 0) {
      for (let i = 0; i < arg.length; i++) {
        if (arg[i] instanceof Array) {
          for (let j = 0; j < arg[i].length; j++) {
            newArray.push(arg[i][j])
          }
        }
      }
      return newArray;
    } else {
      return;
    }
  }

  checkLogin(referrer = config.checkLogin.defaultReferrer, isTab = config.checkLogin.isTab, isDiaog = true, title = '授权后才能操作哦', content = '是否立即授权') {
    const user = wx.getStorageSync(config.checkLogin.keyUser);
    if (user == '' || user == undefined || user == null) {
      wx.setStorageSync('pagesUrl', referrer)
      wx.setStorageSync(config.checkLogin.keyReferrer, {
        path: referrer,
        tab: isTab
      });
      if (isDiaog) {
        // this.confirm({
        //   title: title,
        //   content: content,
        //   confirmText: '去授权',
        //   success: function(res) {
        //     if (res.confirm) {
        //       wx.switchTab({
        //         url: config.checkLogin.loginPath,
        //       })
        //     } else {
        //       wx.navigateBack()
        //     }
        //   }
        // })
        return false;
      } else {
        wx.switchTab({
          url: config.checkLogin.loginPath,
        })
      }
    }
    return user;
  }
  alert(opt) {
    const defaultOpt = {
      showCancel: false,
      confirmColor: config.mainColor
    }
    opt = Object.assign(defaultOpt, opt)
    wx.showModal(opt)
  }

  confirm(opt) {
    const defaultOpt = {
      confirmColor: config.mainColor
    }
    opt = Object.assign(defaultOpt, opt);
    console.log(opt)
    wx.showModal(opt);
  }
  randomString(length = 10) {
    const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    const maxPos = chars.length;
    let str = '';　　
    for (let i = 0; i < length; i++) {
      str += chars.charAt(Math.floor(Math.random() * maxPos));　　
    }
    return str;
  }
  fomatFloat(x, pos = 2) {
    var f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    f = Math.round(x * Math.pow(10, pos)) / Math.pow(10, pos);
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + pos) {
      s += '0';
    }
    return s;
  }

  //转义字符函数
  decodeHtml(s){
    return s.replace(s ? /&(?!#?\w+;)/g : /&/g, '&amp;').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, '\'');
  }
}
module.exports = Honey;